<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>MyDy后端 - 日志管理</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        body {
            font-family: 'Helvetica Neue', Arial, sans-serif;
            line-height: 1.6;
            color: #333;
            background-color: #f7f9fc;
            padding: 20px;
        }
        .container {
            max-width: 1200px;
            margin: 0 auto;
            background-color: #fff;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
            overflow: hidden;
        }
        header {
            background-color: #2196F3;
            color: white;
            padding: 20px;
            text-align: center;
        }
        h1 {
            font-size: 24px;
            font-weight: 500;
        }
        .content {
            padding: 20px;
        }
        .controls {
            margin-bottom: 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
        }
        .stats-card {
            background-color: #ebf7ff;
            border-radius: 5px;
            padding: 15px;
            margin-bottom: 20px;
            border-left: 4px solid #2196F3;
        }
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 10px;
            margin-top: 10px;
        }
        .stat-item {
            background-color: white;
            padding: 10px;
            border-radius: 5px;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
        }
        .stat-value {
            font-size: 18px;
            font-weight: bold;
            color: #2196F3;
        }
        .tabs {
            display: flex;
            border-bottom: 1px solid #ddd;
            margin-bottom: 15px;
        }
        .tab {
            padding: 10px 20px;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        .tab.active {
            border-bottom: 2px solid #2196F3;
            color: #2196F3;
            font-weight: 500;
        }
        .tab:hover {
            background-color: #f5f5f5;
        }
        .log-container {
            background-color: #1e1e1e;
            color: #f0f0f0;
            padding: 15px;
            border-radius: 5px;
            height: 600px;
            overflow-y: auto;
            font-family: 'Consolas', monospace;
            font-size: 14px;
            line-height: 1.5;
        }
        .log-line {
            white-space: pre-wrap;
            word-break: break-all;
            margin-bottom: 2px;
        }
        .log-line.error {
            color: #f44336;
        }
        .log-line.warning {
            color: #ffc107;
        }
        .log-line.info {
            color: #4caf50;
        }
        .login-form {
            max-width: 400px;
            margin: 40px auto;
            padding: 20px;
            background-color: white;
            border-radius: 5px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        .form-group {
            margin-bottom: 15px;
        }
        label {
            display: block;
            margin-bottom: 5px;
            font-weight: 500;
        }
        input {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 16px;
        }
        button {
            background-color: #2196F3;
            color: white;
            border: none;
            padding: 10px 15px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
            transition: background-color 0.3s;
        }
        button:hover {
            background-color: #0d8aee;
        }
        .hidden {
            display: none;
        }
        .buttons {
            display: flex;
            gap: 10px;
        }
        .error-message {
            color: #f44336;
            margin-top: 10px;
        }
        .timestamp {
            color: #888;
            font-size: 12px;
        }
        .refresh-bar {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-top: 20px;
        }
        footer {
            text-align: center;
            padding: 20px;
            color: #666;
            font-size: 14px;
            border-top: 1px solid #eee;
        }
    </style>
</head>
<body>
    <div class="container">
        <header>
            <h1>MyDy后端 - 日志管理系统</h1>
            <p>管理员专用</p>
        </header>
        
        <div id="login-section" class="content">
            <div class="login-form">
                <h2>管理员登录</h2>
                <div class="form-group">
                    <label for="username">用户名</label>
                    <input type="text" id="username" placeholder="请输入管理员用户名">
                </div>
                <div class="form-group">
                    <label for="password">密码</label>
                    <input type="password" id="password" placeholder="请输入密码">
                </div>
                <button id="login-btn">登录</button>
                <p id="login-error" class="error-message hidden"></p>
            </div>
        </div>
        
        <div id="logs-section" class="content hidden">
            <div class="controls">
                <div class="buttons">
                    <button id="refresh-btn">刷新日志</button>
                    <button id="logout-btn">退出登录</button>
                </div>
                <div class="timestamp">
                    最后更新: <span id="last-update">-</span>
                </div>
            </div>
            
            <div class="stats-card">
                <h2>日志统计信息</h2>
                <div class="stats-grid">
                    <div class="stat-item">
                        <div>访问日志行数</div>
                        <div class="stat-value" id="access-lines">-</div>
                    </div>
                    <div class="stat-item">
                        <div>错误日志行数</div>
                        <div class="stat-value" id="error-lines">-</div>
                    </div>
                    <div class="stat-item">
                        <div>数据库日志行数</div>
                        <div class="stat-value" id="db-lines">-</div>
                    </div>
                    <div class="stat-item">
                        <div>今日API请求</div>
                        <div class="stat-value" id="today-requests">-</div>
                    </div>
                    <div class="stat-item">
                        <div>今日错误数</div>
                        <div class="stat-value" id="today-errors">-</div>
                    </div>
                </div>
            </div>
            
            <div class="tabs">
                <div class="tab active" data-log-type="access">访问日志</div>
                <div class="tab" data-log-type="error">错误日志</div>
                <div class="tab" data-log-type="db">数据库日志</div>
            </div>
            
            <div class="log-container" id="log-viewer">
                <div class="log-line">加载中，请稍候...</div>
            </div>
            
            <div class="refresh-bar">
                <span>日志将每30秒自动刷新一次</span>
                <button id="clear-logs">清空显示</button>
            </div>
        </div>
        
        <footer>
            <p>MyDy后端服务 - 日志管理系统 &copy; 2024</p>
            <p>部署于宝塔面板</p>
        </footer>
    </div>
    
    <script>
        // 全局变量
        let authToken = '';
        let currentLogType = 'access';
        let refreshInterval;
        
        // DOM元素
        const loginSection = document.getElementById('login-section');
        const logsSection = document.getElementById('logs-section');
        const loginBtn = document.getElementById('login-btn');
        const loginError = document.getElementById('login-error');
        const usernameInput = document.getElementById('username');
        const passwordInput = document.getElementById('password');
        const logoutBtn = document.getElementById('logout-btn');
        const refreshBtn = document.getElementById('refresh-btn');
        const lastUpdate = document.getElementById('last-update');
        const logViewer = document.getElementById('log-viewer');
        const clearLogsBtn = document.getElementById('clear-logs');
        const tabs = document.querySelectorAll('.tab');
        
        // 统计数据元素
        const accessLinesEl = document.getElementById('access-lines');
        const errorLinesEl = document.getElementById('error-lines');
        const dbLinesEl = document.getElementById('db-lines');
        const todayRequestsEl = document.getElementById('today-requests');
        const todayErrorsEl = document.getElementById('today-errors');
        
        // 格式化字节大小
        function formatBytes(bytes, decimals = 2) {
            if (bytes === 0) return '0 Bytes';
            const k = 1024;
            const dm = decimals < 0 ? 0 : decimals;
            const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
            const i = Math.floor(Math.log(bytes) / Math.log(k));
            return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
        }
        
        // 登录函数
        function login() {
            const username = usernameInput.value.trim();
            const password = passwordInput.value.trim();
            
            if (!username || !password) {
                showLoginError('用户名和密码不能为空');
                return;
            }
            
            fetch('/login', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ username, password })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success && data.userType === 'admin') {
                    authToken = data.token;
                    localStorage.setItem('authToken', authToken);
                    showLogsSection();
                    fetchLogStats();
                    fetchLogs(currentLogType);
                    startAutoRefresh();
                } else {
                    showLoginError('登录失败: 用户名或密码错误，或无管理员权限');
                }
            })
            .catch(error => {
                console.error('登录错误:', error);
                showLoginError('登录失败: 服务器错误');
            });
        }
        
        // 显示登录错误
        function showLoginError(message) {
            loginError.textContent = message;
            loginError.classList.remove('hidden');
        }
        
        // 显示日志部分
        function showLogsSection() {
            loginSection.classList.add('hidden');
            logsSection.classList.remove('hidden');
        }
        
        // 显示登录部分
        function showLoginSection() {
            loginSection.classList.remove('hidden');
            logsSection.classList.add('hidden');
            stopAutoRefresh();
        }
        
        // 退出登录
        function logout() {
            authToken = '';
            localStorage.removeItem('authToken');
            showLoginSection();
        }
        
        // 获取日志统计
        function fetchLogStats() {
            fetch('/api/logs/stats/summary', {
                headers: {
                    'Authorization': `Bearer ${authToken}`
                }
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    accessLinesEl.textContent = data.stats.accessLines || 0;
                    errorLinesEl.textContent = data.stats.errorLines || 0;
                    dbLinesEl.textContent = data.stats.dbLines || 0;
                    todayRequestsEl.textContent = data.stats.todayRequests || 0;
                    todayErrorsEl.textContent = data.stats.todayErrors || 0;
                }
            })
            .catch(error => {
                console.error('获取日志统计错误:', error);
            });
        }
        
        // 获取日志内容
        function fetchLogs(type) {
            logViewer.innerHTML = '<div class="log-line">加载中，请稍候...</div>';
            
            fetch(`/api/logs/${type}`, {
                headers: {
                    'Authorization': `Bearer ${authToken}`
                }
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    logViewer.innerHTML = '';
                    lastUpdate.textContent = new Date().toLocaleString();
                    
                    if (data.lines && data.lines.length > 0) {
                        data.lines.forEach(line => {
                            if (line.trim()) {
                                const logLine = document.createElement('div');
                                logLine.className = 'log-line';
                                
                                // 根据日志类型添加颜色
                                if (type === 'error' || line.includes('错误') || line.includes('Error')) {
                                    logLine.classList.add('error');
                                } else if (line.includes('警告') || line.includes('Warning')) {
                                    logLine.classList.add('warning');
                                } else if (line.includes('成功') || line.includes('Success')) {
                                    logLine.classList.add('info');
                                }
                                
                                logLine.textContent = line;
                                logViewer.appendChild(logLine);
                            }
                        });
                        
                        // 滚动到底部
                        logViewer.scrollTop = logViewer.scrollHeight;
                    } else {
                        logViewer.innerHTML = '<div class="log-line">暂无日志数据</div>';
                    }
                } else {
                    logViewer.innerHTML = `<div class="log-line error">获取日志失败: ${data.message}</div>`;
                }
            })
            .catch(error => {
                console.error('获取日志错误:', error);
                logViewer.innerHTML = `<div class="log-line error">获取日志错误: ${error.message}</div>`;
            });
        }
        
        // 清空日志显示
        function clearLogDisplay() {
            logViewer.innerHTML = '<div class="log-line">日志已清空，点击刷新以重新加载</div>';
        }
        
        // 开始自动刷新
        function startAutoRefresh() {
            stopAutoRefresh(); // 先停止之前的定时器
            refreshInterval = setInterval(() => {
                fetchLogStats();
                fetchLogs(currentLogType);
            }, 30000); // 每30秒刷新一次
        }
        
        // 停止自动刷新
        function stopAutoRefresh() {
            if (refreshInterval) {
                clearInterval(refreshInterval);
            }
        }
        
        // 事件监听
        loginBtn.addEventListener('click', login);
        logoutBtn.addEventListener('click', logout);
        refreshBtn.addEventListener('click', () => {
            fetchLogStats();
            fetchLogs(currentLogType);
        });
        clearLogsBtn.addEventListener('click', clearLogDisplay);
        
        // 标签切换
        tabs.forEach(tab => {
            tab.addEventListener('click', () => {
                // 移除所有活动标签
                tabs.forEach(t => t.classList.remove('active'));
                // 添加当前活动标签
                tab.classList.add('active');
                // 更新当前日志类型并获取日志
                currentLogType = tab.dataset.logType;
                fetchLogs(currentLogType);
            });
        });
        
        // 回车键登录
        passwordInput.addEventListener('keyup', (event) => {
            if (event.key === 'Enter') {
                login();
            }
        });
        
        // 检查是否已登录
        document.addEventListener('DOMContentLoaded', () => {
            const savedToken = localStorage.getItem('authToken');
            if (savedToken) {
                authToken = savedToken;
                
                // 验证token是否有效
                fetch('/user/info', {
                    headers: {
                        'Authorization': `Bearer ${authToken}`
                    }
                })
                .then(response => response.json())
                .then(data => {
                    if (data.id) {
                        showLogsSection();
                        fetchLogStats();
                        fetchLogs(currentLogType);
                        startAutoRefresh();
                    } else {
                        logout();
                    }
                })
                .catch(() => {
                    logout();
                });
            }
        });
    </script>
</body>
</html> 